<template>
  <view class="game-hall">
    <!-- 顶部导航 -->
    <view class="hall-header">
      <view class="header-title">抓黑枪游戏大厅</view>
      <view class="header-info">
        <text class="user-name">{{ userInfo.nickName || '游客' }}</text>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="hall-stats">
      <view class="stat-item">
        <text class="stat-label">在线人数</text>
        <text class="stat-value">{{ onlineCount }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">房间数量</text>
        <text class="stat-value">{{ roomList.length }}</text>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="hall-actions">
      <button class="btn-primary" @click="createRoom">创建房间</button>
      <button class="btn-default" @click="quickMatch">快速匹配</button>
      <button class="btn-default" @click="refreshRoomList">刷新列表</button>
    </view>

    <!-- 房间列表 -->
    <view class="room-list">
      <view class="list-header">
        <text class="list-title">房间列表</text>
      </view>
      
      <scroll-view scroll-y class="room-scroll" @scrolltolower="loadMore">
        <view v-if="roomList.length > 0">
          <view 
            v-for="room in roomList" 
            :key="room.id" 
            class="room-item"
            @click="joinRoom(room)"
          >
            <view class="room-info">
              <view class="room-name">房间号: {{ room.roomNo }}</view>
              <view class="room-owner">房主: {{ room.ownerName }}</view>
            </view>
            
            <view class="room-status">
              <view class="player-count">
                <text class="count-text">{{ room.playerCount }}/4</text>
              </view>
              <view class="status-badge" :class="[
                room.status === 'playing' ? 'status-playing' : 
                room.playerCount >= 4 ? 'status-full' : 'status-waiting'
              ]">
                {{ room.status === 'playing' ? '游戏中' : 
                   room.playerCount >= 4 ? '已满' : '等待中' }}
              </view>
            </view>
          </view>
        </view>
        
        <view v-else class="empty-list">
          <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
          <text class="empty-text">暂无房间，快来创建一个吧~</text>
        </view>
      </scroll-view>
    </view>

    <!-- 创建房间弹窗 -->
    <uni-popup ref="createRoomPopup" type="center">
      <view class="create-room-modal">
        <view class="modal-header">
          <text class="modal-title">创建房间</text>
        </view>
        
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">房间名称</text>
            <input 
              class="form-input" 
              v-model="roomForm.name" 
              placeholder="请输入房间名称（选填）"
              maxlength="20"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">房间密码</text>
            <input 
              class="form-input" 
              v-model="roomForm.password" 
              type="number"
              placeholder="请输入4位密码（选填）"
              maxlength="4"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeCreateModal">取消</button>
          <button class="btn-confirm" @click="confirmCreate">确认创建</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getRoomList, createRoom, joinRoom } from '@/api/game'

export default {
  data() {
    return {
      userInfo: {},
      onlineCount: 0,
      roomList: [],
      roomForm: {
        name: '',
        password: ''
      },
      pageNum: 1,
      pageSize: 20,
      hasMore: true,
      loading: false
    }
  },
  
  onLoad() {
    this.getUserInfo()
    this.loadRoomList()
  },
  
  onShow() {
    // 每次显示页面时刷新房间列表
    this.refreshRoomList()
  },
  
  methods: {
    // 获取用户信息
    getUserInfo() {
      this.userInfo = uni.getStorageSync('userInfo') || {}
    },
    
    // 加载房间列表
    async loadRoomList() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      try {
        const res = await getRoomList({
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        
        if (res.code === 200) {
          // 后端返回的是数组，需要映射字段名
          const rooms = (res.data || []).map(room => ({
            ...room,
            roomNo: room.roomId,        // roomId 映射为 roomNo
            ownerName: room.owner,      // owner 映射为 ownerName
            playerCount: room.currentPlayers,  // currentPlayers 映射为 playerCount
            id: room.roomId            // 添加 id 字段用于列表 key
          }))
          
          if (this.pageNum === 1) {
            this.roomList = rooms
          } else {
            this.roomList = [...this.roomList, ...rooms]
          }
          
          this.onlineCount = res.data.onlineCount || 0
          this.hasMore = rooms.length >= this.pageSize
        }
      } catch (err) {
        console.error('加载房间列表失败', err)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 刷新房间列表
    refreshRoomList() {
      this.pageNum = 1
      this.hasMore = true
      this.loadRoomList()
    },
    
    // 加载更多
    loadMore() {
      if (!this.loading && this.hasMore) {
        this.pageNum++
        this.loadRoomList()
      }
    },
    
    // 创建房间
    createRoom() {
      this.$refs.createRoomPopup.open()
    },
    
    // 关闭创建房间弹窗
    closeCreateModal() {
      this.roomForm = {
        name: '',
        password: ''
      }
      this.$refs.createRoomPopup.close()
    },
    
    // 确认创建
    async confirmCreate() {
      try {
        uni.showLoading({ title: '创建中...' })
        
        const res = await createRoom(this.roomForm)
        
        uni.hideLoading()
        
        if (res.code === 200) {
          uni.showToast({
            title: '创建成功',
            icon: 'success'
          })
          
          this.closeCreateModal()
          
          // 跳转到房间页面（后端返回的是 roomId 字段）
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/game/room/index?roomId=${res.data.roomId}`
            })
          }, 500)
        } else {
          uni.showToast({
            title: res.msg || '创建失败',
            icon: 'none'
          })
        }
      } catch (err) {
        uni.hideLoading()
        console.error('创建房间失败', err)
        
        // 显示具体的错误信息
        let errorMsg = '创建失败'
        if (err.message) {
          errorMsg = err.message
        } else if (typeof err === 'string') {
          errorMsg = err
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 快速匹配
    async quickMatch() {
      uni.showToast({
        title: '正在匹配...',
        icon: 'loading'
      })
      
      // TODO: 实现快速匹配逻辑
      setTimeout(() => {
        uni.showToast({
          title: '暂无可匹配的房间',
          icon: 'none'
        })
      }, 1000)
    },
    
    // 加入房间
    async joinRoom(room) {
      if (room.playerCount >= 4) {
        uni.showToast({
          title: '房间已满',
          icon: 'none'
        })
        return
      }
      
      if (room.status === 'playing') {
        uni.showToast({
          title: '游戏进行中',
          icon: 'none'
        })
        return
      }
      
      // 如果有密码，需要输入密码
      if (room.hasPassword) {
        uni.showModal({
          title: '输入密码',
          editable: true,
          placeholderText: '请输入房间密码',
          success: async (res) => {
            if (res.confirm) {
              await this.doJoinRoom(room.id, res.content)
            }
          }
        })
      } else {
        await this.doJoinRoom(room.id)
      }
    },
    
    // 执行加入房间
    async doJoinRoom(roomId, password) {
      try {
        uni.showLoading({ title: '加入中...' })
        
        const res = await joinRoom(roomId, password)
        
        uni.hideLoading()
        
        if (res.code === 200) {
          uni.showToast({
            title: '加入成功',
            icon: 'success'
          })
          
          // 跳转到房间页面
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/game/room/index?roomId=${roomId}`
            })
          }, 500)
        } else {
          uni.showToast({
            title: res.msg || '加入失败',
            icon: 'none'
          })
        }
      } catch (err) {
        uni.hideLoading()
        console.error('加入房间失败', err)
        
        // 显示具体的错误信息
        let errorMsg = '加入失败'
        if (err.message) {
          errorMsg = err.message
        } else if (typeof err === 'string') {
          errorMsg = err
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 获取房间状态样式类
  }
}
</script>

<style lang="scss" scoped>
.game-hall {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 20rpx;
}

.hall-header {
  background: rgba(255, 255, 255, 0.95);
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
  
  .header-info {
    .user-name {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.hall-stats {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  
  .stat-item {
    flex: 1;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16rpx;
    padding: 30rpx;
    text-align: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .stat-label {
      display: block;
      font-size: 26rpx;
      color: #999;
      margin-bottom: 10rpx;
    }
    
    .stat-value {
      display: block;
      font-size: 40rpx;
      font-weight: bold;
      color: #667eea;
    }
  }
}

.hall-actions {
  display: flex;
  padding: 0 30rpx 30rpx;
  gap: 20rpx;
  
  button {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .btn-primary {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: #fff;
  }
  
  .btn-default {
    background: rgba(255, 255, 255, 0.95);
    color: #667eea;
  }
}

.room-list {
  margin: 0 30rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .list-header {
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;
    
    .list-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .room-scroll {
    height: calc(100vh - 580rpx);
  }
  
  .room-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;
    
    &:active {
      background: #f5f5f5;
    }
    
    .room-info {
      flex: 1;
      
      .room-name {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .room-owner {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .room-status {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .player-count {
        .count-text {
          font-size: 28rpx;
          color: #667eea;
          font-weight: bold;
        }
      }
      
      .status-badge {
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        
        &.status-waiting {
          background: #e8f5e9;
          color: #4caf50;
        }
        
        &.status-full {
          background: #fff3e0;
          color: #ff9800;
        }
        
        &.status-playing {
          background: #ffebee;
          color: #f44336;
        }
      }
    }
  }
  
  .empty-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 30rpx;
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.create-room-modal {
  width: 600rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  
  .modal-header {
    padding: 30rpx;
    text-align: center;
    border-bottom: 1px solid #f0f0f0;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-content {
    padding: 30rpx;
    
    .form-item {
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .form-label {
        display: block;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 15rpx;
      }
      
      .form-input {
        width: 100%;
        height: 80rpx;
        padding: 0 20rpx;
        background: #f5f5f5;
        border-radius: 8rpx;
        font-size: 28rpx;
      }
    }
  }
  
  .modal-footer {
    display: flex;
    border-top: 1px solid #f0f0f0;
    
    button {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      font-size: 28rpx;
      border: none;
      border-radius: 0;
      background: none;
      
      &.btn-cancel {
        color: #999;
        border-right: 1px solid #f0f0f0;
      }
      
      &.btn-confirm {
        color: #667eea;
        font-weight: bold;
      }
    }
  }
}
</style>
